package com.adk.backend.controller;

import com.adk.backend.annotation.RequiresPermission;
import com.adk.backend.service.DownloadService;
import com.adk.backend.util.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 下载中心控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/download")
public class DownloadController {
    
    @Autowired
    private DownloadService downloadService;
    
    @Autowired
    private ExcelUtil excelUtil;
    
    /**
     * 批量下载订单数据
     */
    @RequiresPermission("list")
    @PostMapping("/order-data")
    public void downloadOrderData(
            @RequestParam(required = false) String searchStartDate,
            @RequestParam(required = false) String searchEndDate,
            @RequestParam(required = false, defaultValue = "1") Integer downloadFrom,
            @RequestParam(required = false) Long customerId,
            @RequestParam(required = false) Integer bill,
            @RequestParam(required = false) Long ywId,
            @RequestParam(required = false) Integer shipType,
            @RequestParam(required = false) Integer status,
            HttpServletResponse response) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("searchStartDate", searchStartDate);
            params.put("searchEndDate", searchEndDate);
            params.put("downloadFrom", downloadFrom);
            params.put("customerId", customerId);
            params.put("bill", bill);
            params.put("ywId", ywId);
            params.put("shipType", shipType);
            params.put("status", status);
            params.put("isStopShip", 0); // 不包含停发的订单
            
            List<Map<String, Object>> data = downloadService.downloadOrderData(params);
            
            // 准备表头
            String[] headers = {
                "入库日期", "交货方式", "客户", "入仓号", "送仓类型", "备注", "报关", 
                "箱数", "计费重", "箱/票", "头程单号", "出库日期", "提单号", "最新动态", 
                "时间", "预约状态", "预约时间", "出货方式", "装柜日期", "柜号", "运输方式"
            };
            
            // 转换数据格式
            List<Map<String, Object>> exportData = new ArrayList<>();
            
            for (Map<String, Object> item : data) {
                Map<String, Object> row = new HashMap<>();
                row.put("入库日期", item.get("recv_time"));
                row.put("交货方式", item.get("order_type"));
                row.put("客户", item.get("cus_code"));
                row.put("入仓号", item.get("order_no"));
                row.put("送仓类型", item.get("des_add"));
                row.put("备注", item.get("remarks"));
                row.put("报关", item.get("declare_type"));
                row.put("箱数", item.get("total_ctns"));
                row.put("计费重", item.get("ship_weigth"));
                row.put("箱/票", item.get("shipped_qty"));
                row.put("头程单号", item.get("tx_no"));
                row.put("出库日期", item.get("tx_date"));
                row.put("提单号", item.get("bl_no"));
                row.put("最新动态", item.get("new_status"));
                row.put("时间", item.get("last_status_time"));
                row.put("预约状态", ""); // 需要从booking_list获取
                row.put("预约时间", item.get("booking_date"));
                row.put("出货方式", item.get("shipped_type"));
                row.put("装柜日期", item.get("loading_date"));
                row.put("柜号", item.get("loading_no"));
                row.put("运输方式", item.get("ship_type"));
                exportData.add(row);
            }
            
            // 生成文件名
            String fileName = "Order_List_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            
            // 导出Excel
            excelUtil.exportExcel(response, fileName, headers, exportData);
        } catch (Exception e) {
            log.error("导出订单数据失败", e);
            try {
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().write("导出失败：" + e.getMessage());
            } catch (IOException ioException) {
                log.error("写入错误信息失败", ioException);
            }
        }
    }
    
    /**
     * 批量下载账单数据
     */
    @RequiresPermission("list")
    @PostMapping("/billing-data")
    public void downloadBillingData(
            @RequestParam(required = false) String searchStartDate,
            @RequestParam(required = false) String searchEndDate,
            @RequestParam(required = false, defaultValue = "1") Integer downloadFrom,
            @RequestParam(required = false) Long customerId,
            @RequestParam(required = false) Integer shipType,
            @RequestParam(required = false) Integer status,
            HttpServletResponse response) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("searchStartDate", searchStartDate);
            params.put("searchEndDate", searchEndDate);
            params.put("downloadFrom", downloadFrom);
            params.put("customerId", customerId);
            params.put("shipType", shipType);
            params.put("status", status);
            
            List<Map<String, Object>> data = downloadService.downloadBillingData(params);
            
            // 准备表头
            String[] headers = {
                "Bill_ID", "客户", "入仓号", "入库日期", "账单日期", "货币", "账单金额", 
                "收款状态", "收款日期", "收款账户", "运输方式", "备注", "业务", 
                "签收日期", "账期", "开发", "提单号", "柜号"
            };
            
            // 转换数据格式（已经在Service中转换好了）
            List<Map<String, Object>> exportData = new ArrayList<>();
            for (Map<String, Object> item : data) {
                Map<String, Object> row = new HashMap<>();
                for (String header : headers) {
                    row.put(header, item.get(header));
                }
                exportData.add(row);
            }
            
            // 生成文件名
            String fileName = "账单总览_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            if (downloadFrom == 2) {
                fileName += "_By账单创建日期";
            } else if (downloadFrom == 3) {
                fileName += "_By收款日期";
            } else {
                fileName += "_By入库日期";
            }
            
            // 导出Excel
            excelUtil.exportExcel(response, fileName, headers, exportData);
        } catch (Exception e) {
            log.error("导出账单数据失败", e);
            try {
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().write("导出失败：" + e.getMessage());
            } catch (IOException ioException) {
                log.error("写入错误信息失败", ioException);
            }
        }
    }
    
    @Autowired
    private com.adk.backend.service.CustomerService customerService;
    
    @Autowired
    private com.adk.backend.service.OrderStatusService orderStatusService;
    
    @Autowired
    private com.adk.backend.service.AuthService authService;
    
    /**
     * 获取下载中心页面数据（客户列表、业务员列表、订单状态列表）
     */
    @RequiresPermission("list")
    @GetMapping("/page-data")
    public com.adk.backend.common.Result<Map<String, Object>> getPageData() {
        try {
            Map<String, Object> data = new HashMap<>();
            
            // 获取客户列表（status=1的启用客户）
            java.util.List<com.adk.backend.entity.LxCustomerList> customers = customerService.getAllEnabledCustomers();
            data.put("customers", customers);
            
            // 获取业务员列表（user_type in (4, 6, 35) 且 status=0）
            java.util.List<com.adk.backend.entity.LxAdmin> salesUsers = authService.getSalesUsers();
            data.put("salesUsers", salesUsers);
            
            // 获取订单状态列表
            java.util.List<com.adk.backend.entity.LxOrderStatus> orderStatuses = orderStatusService.getAllStatusList();
            data.put("orderStatuses", orderStatuses);
            
            return com.adk.backend.common.Result.success(data);
        } catch (Exception e) {
            log.error("获取下载中心页面数据失败", e);
            return com.adk.backend.common.Result.error("获取数据失败：" + e.getMessage());
        }
    }
}

